package com.ys.otms.services.impl;

import com.ys.otms.dao.ICompanyDao;
import com.ys.otms.dto.CompanyDto;
import com.ys.otms.services.ICompanyServices;
import com.ys.otms.utils.JsonUtil;
import com.ys.otms.utils.StringUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class CompanyServiceImpl implements ICompanyServices {

    private static Logger logger = LoggerFactory.getLogger(CompanyServiceImpl.class);

    @Autowired
    private ICompanyDao iCompanyDao;

    @Override
    public JSONObject queryCompany(HttpServletRequest request) {
        logger.info("CompanyServiceImpl queryCompany start");
        Integer companyId = Integer.parseInt((String) request.getSession().getAttribute("SESSION_COMPANY_ID"));
        CompanyDto companyDto = iCompanyDao.queryCompany(companyId);

        return JSONObject.fromObject(companyDto);
    }

    @Override
    public JSONObject editCompany(HttpServletRequest request) throws Exception {
        JSONObject obj = JsonUtil.getJSONObject(request);
        logger.info("CompanyServiceImpl editCompany obj：{} ", obj);
        String isManager = (String) request.getSession().getAttribute("SESSION_IS_MANAGER");
        JSONObject retObj = new JSONObject();
        if ("Y".equals(isManager)) {
            Integer companyId = Integer.parseInt((String) request.getSession().getAttribute("SESSION_COMPANY_ID"));
            String address = JsonUtil.getJSONObjectString2(obj,"address");
            String phone = JsonUtil.getJSONObjectString2(obj,"phone");
            String note = JsonUtil.getJSONObjectString2(obj,"note");
            if (StringUtil.isEmpty(address) && StringUtil.isEmpty(phone) && StringUtil.isEmpty(note)) {
                retObj.put("SUCCESS", false);
                retObj.put("MSG","请填写相关信息");
                return retObj;
            }
            String logo = JsonUtil.getJSONObjectString2(obj,"logo");
            CompanyDto companyDto = new CompanyDto(companyId, address, phone, note, logo);
            iCompanyDao.updateCompany(companyDto);
            retObj.put("SUCCESS", true);
            retObj.put("MSG","修改成功");
        }
        else {
            retObj.put("SUCCESS", false);
            retObj.put("MSG","修改失败，您不是管理员，请联系管理员！");
        }

        return retObj;
    }
}
